Page({
  data: {
    id: null,
    member: null,
    loading: true,
    activeTab: 'records',
    healthRecords: [],
    healthReports: [],
    reminders: []
  },

  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id
      })
      this.loadMemberData(options.id)
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },
  
  onShow: function() {
    // 页面显示时重新加载数据，确保编辑后能显示最新数据
    if (this.data.id) {
      this.loadMemberData(this.data.id);
    }
  },

  loadMemberData: function (id) {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }

    this.setData({ loading: true });
    
    // 获取家庭成员详情
    wx.request({
      url: `http://localhost:3000/api/members/${id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        console.log('成员详情响应:', res.data);
        
        if (res.data.success) {
          const memberData = res.data.data.member;
          
          // 计算BMI
          let bmi = '';
          if (memberData.height && memberData.weight) {
            const heightInMeters = memberData.height / 100;
            bmi = (memberData.weight / (heightInMeters * heightInMeters)).toFixed(1);
          }
          
          // 格式化成员数据
          const member = {
            id: memberData.id,
            name: memberData.name,
            avatar: memberData.avatar || '',
            age: memberData.age || '未知',
            gender: memberData.gender || '未知',
            height: memberData.height || '未知',
            weight: memberData.weight || '未知',
            birthday: memberData.birth_date || memberData.birthday || '未知',
            bloodType: memberData.blood_type || '未知',
            healthStatus: memberData.health_status || 'normal',
            bmi: bmi || '未知',
            relationship: memberData.relationship || '未知'
          };
          
          this.setData({
            member: member
          });
          
          // 加载健康记录
          this.loadHealthRecords(id);
          
          // 加载健康提醒
          this.loadReminders(id);
          
          // 加载健康报告（如果有API）
          this.loadHealthReports(id);
        } else {
          console.error('获取成员详情失败:', res.data.message);
          wx.showToast({
            title: res.data.message || '获取成员数据失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },
  
  // 加载健康记录
  loadHealthRecords: function(memberId) {
    const token = wx.getStorageSync('token');
    
    wx.request({
      url: `http://localhost:3000/api/records?memberId=${memberId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        console.log('健康记录响应:', res.data);
        
        if (res.data.success) {
          const records = res.data.data.records || [];
          
          // 按类型分组记录
          const recordGroups = {};
          records.forEach(record => {
            if (!recordGroups[record.type]) {
              recordGroups[record.type] = [];
            }
            
            // 提取日期和时间
            let date = '';
            let time = '';
            if (record.record_time) {
              const recordTime = new Date(record.record_time);
              date = recordTime.toISOString().split('T')[0];
              time = recordTime.toTimeString().substring(0, 5);
            }
            
            recordGroups[record.type].push({
              id: record.id,
              value: record.value,
              date: date,
              time: time
            });
          });
          
          // 转换为数组格式
          const healthRecords = Object.keys(recordGroups).map(type => ({
            type: type,
            records: recordGroups[type]
          }));
          
          this.setData({
            healthRecords: healthRecords,
            loading: false
          });
        } else {
          console.error('获取健康记录失败:', res.data.message);
          this.setData({ loading: false });
        }
      },
      fail: (err) => {
        console.error('请求健康记录失败:', err);
        this.setData({ loading: false });
      }
    });
  },
  
  // 加载健康提醒
  loadReminders: function(memberId) {
    const token = wx.getStorageSync('token');
    
    wx.request({
      url: `http://localhost:3000/api/reminders?memberId=${memberId}&status=active`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        console.log('健康提醒响应:', res.data);
        
        if (res.data.success) {
          const reminders = (res.data.data.reminders || []).map(item => {
            // 处理重复类型
            let repeat = '一次性';
            if (item.repeatType === 'daily') {
              repeat = '每天';
            } else if (item.repeatType === 'weekly' && item.days && item.days.length > 0) {
              repeat = `每周${item.days.join('、')}`;
            } else if (item.repeatType === 'monthly') {
              repeat = '每月';
            }
            
            return {
              id: item.id,
              title: item.title,
              content: item.content || '',
              time: item.time,
              date: item.date,
              repeat: repeat,
              active: item.active
            };
          });
          
          this.setData({
            reminders: reminders
          });
        } else {
          console.error('获取健康提醒失败:', res.data.message);
        }
      },
      fail: (err) => {
        console.error('请求健康提醒失败:', err);
      }
    });
  },
  
  // 加载健康报告
  loadHealthReports: function(memberId) {
    // 健康报告接口可能尚未实现，使用空数据
    this.setData({
      healthReports: []
    });
  },

  // 查看更多健康记录
  viewMoreRecords: function() {
    console.log('查看更多记录被点击，member ID:', this.data.id, '成员信息:', this.data.member);
    
    if (!this.data.id || !this.data.member) {
      wx.showToast({
        title: '无法获取成员信息',
        icon: 'none'
      });
      return;
    }
    
    // 将成员ID保存到本地存储，确保记录页面能获取
    const memberId = this.data.id;
    wx.setStorageSync('selectedMemberId', memberId);
    
    // 显示加载提示
    wx.showLoading({
      title: '正在加载记录...',
    });
    
    // 使用switchTab而不是navigateTo，因为records是tabBar页面
    wx.switchTab({
      url: '/pages/records/records',
      success: () => {
        console.log(`成功跳转到健康记录页面，并选中成员ID: ${memberId}`);
        setTimeout(() => {
          wx.hideLoading();
        }, 500);
      },
      fail: (err) => {
        console.error('跳转到健康记录页面失败:', err);
        wx.hideLoading();
        
        wx.showToast({
          title: '页面跳转失败，请稍后再试',
          icon: 'none'
        });
      }
    });
  },
  
  // 设置健康提醒
  setupReminder: function() {
    wx.navigateTo({
      url: `/pages/reminders/add/add?memberId=${this.data.id}`
    });
  },

  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      activeTab: tab
    })
  },

  addHealthRecord: function () {
    wx.navigateTo({
      url: `/pages/records/add/add?memberId=${this.data.id}`
    })
  },

  viewHealthReport: function (e) {
    const index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: `/pages/reports/detail/detail?memberId=${this.data.id}&reportIndex=${index}`
    })
  },
  
  viewHealthRecord: function (e) {
    const recordId = e.currentTarget.dataset.id;
    const recordType = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: `/pages/records/detail/detail?id=${recordId}&type=${encodeURIComponent(recordType)}&memberId=${this.data.id}`
    })
  },
  
  // 编辑成员信息
  editMember: function() {
    wx.navigateTo({
      url: `/pages/members/edit/edit?id=${this.data.id}`
    })
  },
  
  // 编辑提醒
  editReminder: function(e) {
    const reminderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/reminders/edit/edit?id=${reminderId}&memberId=${this.data.id}`
    });
  },
  
  // 删除提醒
  deleteReminder: function(e) {
    const reminderId = e.currentTarget.dataset.id;
    const reminderTitle = e.currentTarget.dataset.title;
    
    console.log('尝试删除提醒:', { reminderId, reminderTitle });
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${reminderTitle}"提醒吗？`,
      success: (res) => {
        if (res.confirm) {
          const token = wx.getStorageSync('token');
          
          // 显示加载提示
          wx.showLoading({
            title: '正在删除...',
            mask: true
          });
          
          wx.request({
            url: `http://localhost:3000/api/reminders/${reminderId}`,
            method: 'DELETE',
            header: {
              'Authorization': `Bearer ${token}`
            },
            success: (res) => {
              wx.hideLoading();
              console.log('删除提醒响应:', res.data);
              
              if (res.data.success) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                
                // 重新加载提醒列表
                this.loadReminders(this.data.id);
              } else {
                console.error('删除提醒失败:', res.data.message);
                wx.showToast({
                  title: res.data.message || '删除失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            },
            fail: (err) => {
              wx.hideLoading();
              console.error('删除提醒请求失败:', err);
              wx.showToast({
                title: '网络错误，请稍后重试',
                icon: 'none',
                duration: 2000
              });
            }
          });
        }
      }
    });
  },
   
  addReminder: function () {
    wx.navigateTo({
      url: `/pages/reminders/add/add?memberId=${this.data.id}`
    })
  },

  addReminder: function () {
    wx.navigateTo({
      url: `/pages/reminders/add/add?memberId=${this.data.id}`
    })
  }
}) 